<template>
  <van-popup position="bottom" round v-model:show="show" closeable>
    <div class="add-wrap">
      <div class="head">
        <div class="left">
          <span @click="changeType('expense')" :class="{ active: payType === 'expense' }">支出</span>
          <span @click="changeType('income')" :class="{ active: payType === 'income' }">收入</span>
        </div>
        <div class="right" @click="showTime = true">
          <span>{{ date[1] }}月{{ date[2] }}日 <van-icon name="play" style="transform: rotate(90deg);" /></span>
        </div>
      </div>
      <div class="money">
        <span class="icon">¥</span>
        <span class="amount">{{ amount }}</span>
      </div>
      <div class="type-wrap">
        <div class="expense grid" v-if="payType === 'expense'">
          <div class="item" v-for="item in expense" @click="selectType(item)">
            <i class="iconfont" :class="[iocns[item.name], currentType.id === item.id ? 'is-active' : '']"></i>
            <p>{{ item.name }}</p>
          </div>
        </div>
        <div class="income grid" v-else>
          <div class="item" v-for="item in income" @click="selectType(item)">
            <i class="iconfont" :class="[iocns[item.name], currentType.id === item.id ? 'is-active' : '']"></i>
            <p>{{ item.name }}</p>
          </div>
        </div>
      </div>
      <div class="remark">
        <input type="text" placeholder="添加备注" v-model="remark" />
      </div>
      <div class="keyboard">
        <van-number-keyboard show theme="custom" extra-key="." close-button-text="确定" @input="onInput"
          @delete="onDelete" @close="addBill" />
      </div>
    </div>
  </van-popup>

  <van-popup position="bottom" round v-model:show="showTime">
    <van-date-picker v-model="currentDate" title="选择日期" :min-date="new Date(2020, 2, 1)" :max-date="new Date()"
      @cancel="() => showTime = false" @confirm="selectTime" />
  </van-popup>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { showToast } from 'vant'
import iocns from '@/utils/icons.js';
import formateDate from '@/utils/date.js';
import axios from '@/api/index.js'
import { watch } from 'vue';

const props = defineProps({
  billDetail: {
    type: Object,
    default: () => ({})
  }
})

watch(() => props.billDetail.pay_type, (newVal) => {
  if (newVal === 2) {
    payType.value = 'income';
  } else {
    payType.value = 'expense';
  }
  date.value = formateDate(new Date(Number(props.billDetail.date)));
  currentType.value = { id: props.billDetail.type_id, name: props.billDetail.type_name };
  amount.value = props.billDetail.amount;
  remark.value = props.billDetail.remark;
})

const expense = ref([]);
const income = ref([]);
const payType = ref('expense');
const currentDate = ref(formateDate(new Date()).slice(0, 3));
const date = ref(formateDate(new Date()).slice(0, 3))
const currentType = ref({});  //当前选中的类型
const remark = ref(''); //备注
const amount = ref('');

const show = ref(false);
const showTime = ref(false);

const emit = defineEmits(['onRefresh'])

const onInput = (val) => {
  if (val == '.' && amount.value.includes('.')) return;
  if (amount.value.includes('.') && amount.value.split('.')[1].length >= 2) return;
  amount.value += val;
}

const onDelete = () => {
  amount.value = amount.value.slice(0, -1);
}

const addBill = async () => {
  if (Number.isNaN(Number(amount.value)) || amount.value === '') {
    showToast('请输入正确金额')
    return
  }

  const params = {
    amount: Number(amount.value).toFixed(2),
    remark: remark.value,
    date: new Date(date.value.slice(0, 3).join('-')).getTime(),
    type_id: currentType.value.id,
    type_name: currentType.value.name,
    pay_type: payType.value === 'expense' ? 1 : 2,
    id: props.billDetail.id
  }

  if (props.billDetail.id) {
    await axios.post('/api/bill/update', params)
  } else {
    await axios.post('/api/bill/add', params)
    //清空数据
    amount.value = '';
    remark.value = '';
    currentType.value = expense.value[0];
    payType.value = 'expense';
    date.value = formateDate(new Date());
  }

  show.value = false;

  //促使父组件重新请求数据
  emit('onRefresh')



}
const changeType = (type) => {
  payType.value = type;
}

const selectTime = () => {
  console.log(currentDate.value);
  date.value = currentDate.value;
  console.log(date.value[2]);
  showTime.value = false;
}

const selectType = (type) => {
  console.log(type);
  currentType.value = type;
  console.log(currentType.value);
}

onMounted(async () => {
  // /api/type/list
  const res = await axios.get('/api/type/list')
  console.log(res);
  expense.value = res.data.list.filter(item => item.type === '1');
  income.value = res.data.list.filter(item => item.type === '2');
  currentType.value = expense.value[0];

  if (props.billDetail.id) {
    currentType.value = { id: props.billDetail.type_id, name: props.billDetail.type_name };
  }
});

defineExpose({
  show
})

</script>

<style lang="less" scoped>
.add-wrap {
  padding: 60px 20px 0px;

  .head {
    display: flex;
    justify-content: space-between;

    span {
      padding: 5px 10px;
      background-color: rgb(245, 245, 245);
      margin-right: 10px;
      border-radius: 4px;
      color: #666;
    }
  }

  .money {
    padding: 30px 0;
    font-size: 30px;
    font-weight: bold;
    border-bottom: 1px solid #f1f1f1;

    .amount {
      margin-left: 10px;
    }
  }

  .type-wrap {
    margin: 10px 0;
    height: 110px;
    overflow-y: scroll;

    .grid {
      display: grid;
      grid-template-columns: repeat(6, 1fr);
      text-align: center;
      grid-column-gap: 20px;
      grid-row-gap: 10px;

      .iconfont {
        width: 30px;
        height: 30px;
        display: inline-block;
        line-height: 30px;
        border-radius: 50%;
        text-align: center;
        background-color: #eee;
        color: #000000;
        margin-bottom: 5px;

        &.is-active {
          background-color: #37a762;
          color: #fff;
        }
      }

    }
  }

  .remark {
    margin: 15px 0;

    input {
      width: 100%;
      border-radius: 4px;
      border: none;
      padding: 5px 0px;
      box-sizing: border-box;
      font-size: 16px;
    }
  }

  .keyboard {
    height: 244px;
  }

  .active {
    background-color: rgb(230, 247, 238) !important;
    color: #37a762 !important;
  }
}
</style>